package com.cml.rpc.client;

import com.cml.rpc.common.RpcRequest;
import com.cml.rpc.common.RpcResponse;
import com.cml.rpc.register.ServiceRegister;
import com.cml.rpc.register.ZkServiceRegister;
import com.cml.rpc.server.SimpleRpcServer;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * 低性能的BIO方式
 * @author cml
 * @create 2021/7/21 11:47
 */
public class SimpleRpcClient implements RpcClient{
    private ServiceRegister serviceRegister;
    private int port;
    private String host;

    public SimpleRpcClient(){
        this.serviceRegister = new ZkServiceRegister();
    }

    public SimpleRpcClient(String host, int port) {
        this.port = port;
        this.host = host;
    }
    @Override
    public RpcResponse sendRequest(RpcRequest rpcRequest) {
        try {
            // 使用服务注册中心
            if (serviceRegister != null) {
                InetSocketAddress address = serviceRegister.serviceDiscover(rpcRequest.getInterfaceName());
                host = address.getHostString();
                port = address.getPort();
            }
            System.out.println("--------使用simple客户端----------");
            // 建立socket连接
            Socket socket = new Socket(host, port);
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            // 向客户端发送请求
            System.out.println("客户端发送的rpcRequest = " + rpcRequest);
            oos.writeObject(rpcRequest);
            oos.flush();
            // 接收服务端的响应
            RpcResponse result = (RpcResponse)ois.readObject();
            return result;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("服务启动失败");
            return null;
        }
    }
}
